#include "Engine.h"


std::auto_ptr<TSS::Engine> g_engine(new TSS::Engine);


//needed for closing via x
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	if(msg == WM_DESTROY) 
		PostQuitMessage(0);

	return DefWindowProc(hwnd, msg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
	debug << "WinMain running" << std::endl;
	srand((unsigned int)time(0));

	//check command line
	debug << "Checking command line params" << std::endl;
	if(strlen(lpCmdLine) > 0)
	{
		g_engine->setCommandLineParams(lpCmdLine);
		debug << "Params: " << g_engine->getCommandLineParams() << std::endl;
	}

	debug << "Calling game_preload" << std::endl;
	if(!Game_Preload())
	{
		debug << "Error in game_preload" << std::endl;
		return 0;
	}

	debug << "Initializing engine" << std::endl;
	bool res = g_engine->Init(hInstance, g_engine->getScreenWidth(), g_engine->getScreenHeight(), g_engine->getColorDepth(), g_engine->getFullscreen());
	if(!res)
	{
		debug << "Error initializing the engine" << std::endl;
		return 0;
	}

	MSG msg;
	memset(&msg, 0, sizeof(msg));

	TSS::Timer time;
	double startTime = time.getElapsedTime();

	debug << "Core timer started: " << startTime << std::endl;
	debug << "Entering message loop" << std::endl;

	//main message loop
	while(msg.message != WM_QUIT)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			double t = time.getElapsedTime();
			double deltaTime = (t - startTime) * 0.001f;
			g_engine->Update(deltaTime);
			startTime = t;
		}
	}

	debug << "Exiting while loop" << std::endl;
	debug << "Total run time: " << time.getElapsedTime() << std::endl;
	debug << "Freeing game resources" << std::endl;
	Game_End();

	debug << "Shutting down engine" << std::endl;
	ShowCursor(true);
	return 1;

}